/*
 * Copyright (c) Huawei Device Co., Ltd. 2024. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "response_all_ref_ar_do.h"
#include "common_utils.h"

namespace OHOS {
namespace SE {
using namespace std;

/*
 * Software that is part of the Secure Element access API, it obtains access
 * rules from the Secure Element and applies those rules to restrict device
 * application access to the various Secure Element applications.
 */
ResponseAllRefArDo::ResponseAllRefArDo(std::vector<uint8_t> rawData)
    : BerTlv(rawData, RESPONSE_ALL_REF_AR_DO_TAG)
{
    rawData_ = rawData;
    doTag_ = RESPONSE_ALL_REF_AR_DO_TAG;
}

ResponseAllRefArDo::ResponseAllRefArDo(std::vector<uint8_t> payload, bool isPayload)
    : BerTlv(payload, isPayload, RESPONSE_ALL_REF_AR_DO_TAG)
{
    doTag_ = RESPONSE_ALL_REF_AR_DO_TAG;
    GetRawData(rawData_);
}

ResponseAllRefArDo::~ResponseAllRefArDo()
{
}

bool ResponseAllRefArDo::GetRefArDo(vector<RefArDo> &retRefArDo)
{
    std::string strRawData = CommonUtils::BytesArrayToHexString(&rawData_[0], rawData_.size());
    InfoLog("enter strRawData = %{public}s", strRawData.c_str());
    uint32_t tag;
    if (!GetDoTag(tag) || tag != RESPONSE_ALL_REF_AR_DO_TAG) {
        ErrorLog("tag %{public}d.", tag);
        return false;
    }
    vector<uint8_t> payload;
    if (!GetDoPayload(payload)) {
        return false;
    }
    // parse refardo from payload
    if (payload.empty() || payload.size() == 0) {
        ErrorLog("No REF_AR_DO.");
        return false;
    }
    std::vector<uint8_t> refArDoData;
    uint32_t cnt = 0;
    for (auto it = payload.begin(); it != payload.end();)  {
        // is ref ar do
        if (*it == REF_AR_DO_TAG) {
            // get length
            std::vector<uint8_t> tmpForData;
            std::vector<uint8_t> tmpForRefArDoData;
            uint32_t startForIndex;
            uint32_t forLength;
            tmpForData.assign(it + 1, payload.end());
            ParseLength(tmpForData, forLength, startForIndex);
            tmpForRefArDoData.assign(it, it + 1 + startForIndex + forLength);
            it = it + forLength;
            retRefArDo.push_back(tmpForRefArDoData);
            std::string strRefArDoFor = CommonUtils::BytesArrayToHexString(&tmpForRefArDoData[0],
                tmpForRefArDoData.size());
            cnt++;
        } else {
            it++;
        }
    }
    return true;
}

}  // namespace SE
}  // namespace OHOS
